/*
 * CookbookDesktopApp.java
 */

package cookbookdesktop;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JFileChooser;
import org.jdesktop.application.Application;
import org.jdesktop.application.SingleFrameApplication;
import other.XMLUtils;

/**
 * The main class of the application.
 */
public class CookbookDesktopApp extends SingleFrameApplication {

    /**
     * At startup create and show the main frame of the application.
     */
    @Override protected void startup() {
        JFileChooser jFileChooser = new JFileChooser();
        jFileChooser.setDialogTitle("Otwórz lub utwórz plik XML z przepisami");
        jFileChooser.setMultiSelectionEnabled(false);
        jFileChooser.setVisible(true);
        int returns = jFileChooser.showOpenDialog(null);
        if (returns == JFileChooser.APPROVE_OPTION) {
            XMLUtils.path = jFileChooser.getSelectedFile().getPath();
            if(!XMLUtils.path.endsWith(".xml")) {
                XMLUtils.path = XMLUtils.path + ".xml";
            }
            File tmp = new File(XMLUtils.path);
            if(!tmp.exists()) {
                try {
                    tmp.createNewFile();
                    BufferedWriter w = new BufferedWriter(new FileWriter(tmp));
                    w.write("<vector></vector>");
                    w.close();
                } catch (IOException ex) {
                    Logger.getLogger(CookbookDesktopApp.class.getName()).log(Level.SEVERE, null, ex);
                    System.exit(0);
                }
            }
        } else {
            System.exit(0);
        }
        show(new CookbookDesktopView(this));
    }

    /**
     * This method is to initialize the specified window by injecting resources.
     * Windows shown in our application come fully initialized from the GUI
     * builder, so this additional configuration is not needed.
     */
    @Override protected void configureWindow(java.awt.Window root) {
    }

    /**
     * A convenient static getter for the application instance.
     * @return the instance of CookbookDesktopApp
     */
    public static CookbookDesktopApp getApplication() {
        return Application.getInstance(CookbookDesktopApp.class);
    }

    /**
     * Main method launching the application.
     */
    public static void main(String[] args) {
        launch(CookbookDesktopApp.class, args);
    }
}
